/**
 * API 请求封装
 */

class ApiService {
    /**
     * 登录请求
     * @param {string} username - 用户名
     * @param {string} password - 密码
     * @returns {Promise} 登录结果
     */
    static async login(username, password) {
        try {
            const response = await fetch('/api/auth/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, password })
            });
            const data = await response.json();
            
            if (data.token) {
                TokenService.setToken(data.token, data.userInfo);
            }
            
            return data;
        } catch (error) {
            console.error('登录失败:', error);
            throw error;
        }
    }

    /**
     * 发送需要认证的请求
     * @param {string} url - 请求地址
     * @param {object} options - 请求配置
     * @returns {Promise} 请求结果
     */
    static async authenticatedRequest(url, options = {}) {
        const token = TokenService.getToken();
        if (!token) {
            throw new Error('未登录');
        }

        const config = RequestInterceptor.beforeRequest({
            ...options,
            headers: {
                ...options.headers,
                'Authorization': `Bearer ${token}`
            }
        });

        try {
            const response = await fetch(url, config);
            return RequestInterceptor.handleResponse(response);
        } catch (error) {
            console.error('请求失败:', error);
            throw error;
        }
    }
} 